package com.soujiayi.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.soujiayi.adapter.ProductClassifyGridViewAdapter;
import com.soujiayi.adapter.SearchListAdapter;
import com.soujiayi.model.Category;
import com.soujiayi.model.Categorys;
import com.soujiayi.net.AsyncSuggestionNameLoader;
import com.soujiayi.net.HttpRequester;
import com.soujiayi.net.NetworkUtils;
import com.soujiayi.store.DatabaseManager;
import com.soujiayi.util.CommonUtils;
import com.soujiayi.util.Constants;
import com.soujiayi.view.NetworkUnavailableDialog;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

public class TuanSearchActivity extends Activity implements OnClickListener,
		OnItemClickListener, OnFocusChangeListener, TextWatcher {
	private EditText searchText;
	private Button searchBtn, backBtn;
	private ListView searchListView;
	private SearchListAdapter searchListAdapter;
	private ArrayList<HashMap<String, Object>> searchList = new ArrayList<HashMap<String, Object>>();
	private DatabaseManager databaseManager = new DatabaseManager(
			TuanSearchActivity.this);
	private AsyncSuggestionNameLoader asyncSuggestionNameLoader = new AsyncSuggestionNameLoader(
			3);
	private String cancel, search;
	// private boolean isClassifyShowed = true;
	private boolean isFirstShow = true;
	private GridView classifyGridView;
	private TextView tv_tuan_suggest;
	// private ProductClassifyGridViewAdapter classifyGridViewAdapter;
	private ArrayAdapter classifyGridViewAdapter;
	private ArrayList<String> classifyTextData;
	private List<Integer> classifyImageData;
	private HttpRequester httpRequester;
	private Handler handler;
	private Handler searchCategoryHandler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		((MyApplication) this.getApplication()).addActivity(this);
		setContentView(R.layout.tuan_search);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		initViews();
		initActionListeners();
		initValues();
	}

	public void initViews() {
		searchListView = (ListView) findViewById(R.id.lv_tuan_history_suggestion);
		searchBtn = (Button) findViewById(R.id.btn_tuan_search);
		searchText = (EditText) findViewById(R.id.et_tuan_searchText);
		backBtn = (Button) findViewById(R.id.btn_tuansearch_back);
		// if (isClassifyShowed) {
		initClassifyGridView();
		// }
	}

	private void initClassifyGridView() {
		classifyGridView = (GridView) findViewById(R.id.gv_tuan_suggest);
		tv_tuan_suggest = (TextView) findViewById(R.id.tv_tuan_suggest);
		classifyImageData = new ArrayList<Integer>();
		classifyTextData = new ArrayList<String>();
		classifyGridViewAdapter = new ArrayAdapter<String>(this,
				R.layout.tuan_suggest_grid_item, classifyTextData);
		classifyGridView.setAdapter(classifyGridViewAdapter);
		classifyGridView.setSelected(true);
		classifyGridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View item,
					int position, long arg3) {
				if (!NetworkUtils.isNetworkConnected(TuanSearchActivity.this)) {
					Toast.makeText(TuanSearchActivity.this,
							TuanSearchActivity.this.getString(R.string.network_disconnect),
							Toast.LENGTH_SHORT).show();
					return;
				}
				doSearch(classifyTextData.get(position));
				// ////
			}
		});
		searchCategoryHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				// Bundle data = msg.getData();
				// Categorys categorys = (Categorys) data
				// .getSerializable(Constants.CATEGORYS);
				// List<Category> categoryList = categorys.getCategorys();
				//
				// int type = data.getInt(Constants.CATEGORYS_TYPE);
				// switch (type) {
				// case Constants.CATEGORYS_TYPE_ROOT:
				ArrayList<String> keys = (ArrayList<String>) msg.obj;

				if (keys != null && keys.size() > 0) {
					for (String s : keys) {
						classifyTextData.add(s);
					}
					tv_tuan_suggest.setVisibility(View.VISIBLE);
					classifyGridView.setVisibility(View.VISIBLE);
					classifyGridViewAdapter.notifyDataSetChanged();
				} else {
					tv_tuan_suggest.setVisibility(View.GONE);
					classifyGridView.setVisibility(View.GONE);
				}
			}
		};
		httpRequester = new HttpRequester(this,1, searchCategoryHandler);

		if (!NetworkUtils.isNetworkConnected(TuanSearchActivity.this)) {
			Toast.makeText(TuanSearchActivity.this,
					TuanSearchActivity.this.getString(R.string.network_disconnect),
					Toast.LENGTH_SHORT).show();
			tv_tuan_suggest.setVisibility(View.GONE);
			classifyGridView.setVisibility(View.GONE);
		} else {
			httpRequester.getTuanKeyWords(((MyApplication) this
					.getApplication()).getSessionId());
		}

	}

	public void initActionListeners() {
		searchListView.setOnItemClickListener(this);
		searchBtn.setOnClickListener(this);
		searchText.setOnClickListener(this);
		searchText.addTextChangedListener(this);
		searchText.setOnFocusChangeListener(this);
		// 当滚动时收起软键盘
		searchListView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(searchText.getWindowToken(), 0);
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
			}
		});

	}

	public void initValues() {
		searchListAdapter = new SearchListAdapter(this, searchList);
		searchListView.setAdapter(searchListAdapter);
		cancel = this.getResources().getString(R.string.cancel);
		search = this.getResources().getString(R.string.search);
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				Bundle data = msg.getData();
				if (data != null && data.getStringArrayList("keys").size() > 1) {
					searchList.removeAll(searchList);
					searchList.addAll(CommonUtils.convertLStrToLMap(data
							.getStringArrayList("keys")));
					searchListAdapter.notifyDataSetChanged();
				}

			}
		};

	}

	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub
		String key = searchText.getText().toString().trim();
		// if (isClassifyShowed) {
		classifyGridView.setVisibility(View.INVISIBLE);
		tv_tuan_suggest.setVisibility(View.INVISIBLE);
		searchListView.setVisibility(View.VISIBLE);
		// }
		if (null == key || "".equals(key)) {
			showHistory();
		} else {
			showSuggestionNames(key);
		}
		searchBtn.setText(cancel);
	}

	private void showHistory() {
		// if (isClassifyShowed) {
		if (isFirstShow) {// 如果当前是分类搜索视图而且是第一次显示 不显示历史记录
			searchListView.setVisibility(View.INVISIBLE);
			isFirstShow = false;
			return;
		} else {
			searchListView.setVisibility(View.VISIBLE);
			if (classifyGridView != null) {// 隐藏分类搜索
				classifyGridView.setVisibility(View.INVISIBLE);
				tv_tuan_suggest.setVisibility(View.INVISIBLE);
			}
			// }
		}

		String key = searchText.getText().toString();
		if (null == key || "".equals(key.trim())) {
			ArrayList<HashMap<String, Object>> history = databaseManager
					.getSearchHistory(Constants.HISTORY_TYPE_TUAN);
			if (history.size() > 0) {
				searchList.removeAll(searchList);
				searchList.addAll(history);
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put(Constants.SEARCH_LIST_ITEM,
						Constants.SEARCH_LIST_CLEAR_HISTORY_ITEM);
				searchList.add(map);
				searchListAdapter.notifyDataSetChanged();
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				if (imm.isActive()) {
					imm.hideSoftInputFromWindow(TuanSearchActivity.this
							.getCurrentFocus().getWindowToken(),
							InputMethodManager.HIDE_NOT_ALWAYS);
				}
			} else {
				donotShowHistory();
			}
		}
	}

	private void donotShowHistory() {
		searchList.removeAll(searchList);
		searchListAdapter.notifyDataSetChanged();
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.et_tuan_searchText && hasFocus) {
			showHistory();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		String selectedKey = searchList.get(arg2)
				.get(Constants.SEARCH_LIST_ITEM).toString().trim();
		if (null != selectedKey && !selectedKey.equals("")) {
			if (selectedKey.equals(Constants.SEARCH_LIST_CLEAR_HISTORY_ITEM)) {
				databaseManager
						.deleteSearchHistory(Constants.HISTORY_TYPE_TUAN);
				donotShowHistory();
			} else {
				databaseManager.insertSearchHistory(selectedKey,
						Constants.HISTORY_TYPE_TUAN);
				doSearch(selectedKey);
			}
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_tuan_search: {
			if (searchBtn.getText().toString().equals(search)) {
				String key = searchText.getText().toString();
				if (null != key && !"".equals(key.trim())) {
					databaseManager.insertSearchHistory(key,
							Constants.HISTORY_TYPE_TUAN);
				}
				doSearch(key);
			} else if (searchBtn.getText().toString().equals(cancel)) {
				// if (isClassifyShowed) {
				searchListView.setVisibility(View.INVISIBLE);
				classifyGridView.setVisibility(View.VISIBLE);
				tv_tuan_suggest.setVisibility(View.VISIBLE);
				searchBtn.setText(search);
				// } else {
				// this.finish();
				// overridePendingTransition(R.anim.push_down_in,
				// R.anim.push_down_out);
				// }
			}
		}
			break;
		default:
			break;
		}
	}

	// 搜索商品 跳转到商品列表视图
	public void doSearch(String key) {
		TuanSearchActivity.this.setResult(Activity.RESULT_OK, this.getIntent()
				.putExtra(Constants.TUAN_SEARCH_KEY, key));
		TuanSearchActivity.this.finish();
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	private void showSuggestionNames(String key) {
		if (NetworkUtils.isNetworkConnected(this)) {
			searchList.removeAll(searchList);
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put(Constants.SEARCH_LIST_ITEM, key);
			searchList.add(map);
			searchListAdapter.notifyDataSetChanged();
			asyncSuggestionNameLoader.getSuggestioName(this.handler, key);
		} else {
			Toast.makeText(TuanSearchActivity.this,
					TuanSearchActivity.this.getString(R.string.network_disconnect),
					Toast.LENGTH_SHORT).show();
		}
	}

	public void back(View view) {
		this.finish();
		overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		this.finish();
		overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
}
